package com.sxh.gateway.utils;


import com.sxh.gateway.exception.BaseException;
import com.sxh.gateway.model.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

@Component
public class JwtUtil {
    //密钥
    @Value("${jwt.secret-base64}")
    private String base64Secret;
    private SecretKey SECRET_KEY;
    //有效时长
    private static final long EXPIRATION_TIME = 12*60*60*1000L;
    @PostConstruct      //延迟初始化
    public void JwtUtil() {
        this.SECRET_KEY = createKeyFromBase64String(base64Secret);
    }
    private SecretKey createKeyFromBase64String(String base64Secret) {
        byte[] decodedKey = Base64.getDecoder().decode(base64Secret);
        return new SecretKeySpec(decodedKey, SignatureAlgorithm.HS256.getJcaName());
    }
    //解析JWT Token
//    public UserInfo parseToken(String token) {
//        try {
//            Claims claims = Jwts.parser()
//                    .setSigningKey(SECRET_KEY)
//                    .parseClaimsJws(token)
//                    .getBody();
//
//            UserInfo userInfo = new UserInfo();
//            userInfo.setUserId((Long) claims.get("userId"));
//            return userInfo;
//        } catch (ExpiredJwtException e) {
//            throw new BaseException("token已过期");
//        } catch (SignatureException e) {
//            throw new BaseException("无效签名");
//        } catch (Exception e) {
//            throw new BaseException("无效token");
//        }
//    }
    //验证令牌是否有效
    public boolean validateToken(String token) {
        try {
            Jwts.parser()
                    .setSigningKey(SECRET_KEY)
                    .parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
            throw new BaseException("token已过期");
        } catch (SignatureException e) {
            throw new BaseException("无效签名");
        } catch (Exception e) {
            throw new BaseException("无效token");
        }
    }


}
